package jm.mq.boot_mq.conf;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 延迟队列配置类
 * @date 2022/3/10 19:18
 */
@Configuration
public class DelayedQueueConf {

    // 交换机
    private static final String DELAYED_EXCHANGE = "delayed.exchange";

    // 队列
    private static final String DELAYED_QUEUE = "delayed.queue";

    // rotingKey
    private static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    /**
     * 注入队列
     * @return
     */
    @Bean("delayQueue")
    public Queue delayedQueue(){
        return new Queue(DELAYED_QUEUE);
    }


    /**
     * 注入交换机
     * @return
     */
    @Bean
    public CustomExchange delayedExchange(){
        Map<String ,Object> args = new HashMap<>();
        // 延迟类型
        args.put("x-delayed-type","direct");
        /**
         *      1. 名称
         *      2. 类型
         *      3. 是否持久化
         *      4. 是否自动删除
         *      5. 其他参数
         */
        return new CustomExchange(DELAYED_EXCHANGE,"x-delayed-message",
                false,false,args);
    }

    /**
     * 绑定延迟队列和交换机，routingKey
     * @param queue 队列
     * @param customExchange 交换机
     * @return
     */
    @Bean
    public Binding delayQueueBindingDelayExchange(@Qualifier("delayQueue") Queue queue,
                                                  @Qualifier("delayedExchange") CustomExchange customExchange){
        return BindingBuilder.bind(queue).to(customExchange).with(DELAYED_ROUTING_KEY).noargs();
    }

}
